package com.z.redis.command.impl.hash;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisData;
import com.z.redis.datatype.RedisHash;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespInt;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * hdel key field1 [field2…]
 * 删除哈希表key中一个/多个field字段
 */
public class Hdel implements WriteCommand {
    private BytesWrapper key;
    private List<BytesWrapper> fields;

    public CommandType type(){
        return CommandType.hdel;
    }

    @Override
    public void setContent(Resp[] array){
        key = ((BulkString) array[1]).getContent();
        fields = Stream.of(array).skip(2)
                .map(resp -> ((BulkString) resp).getContent())
                .collect(Collectors.toList());
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null) {
            ctx.writeAndFlush(BulkString.NullBulkString);
        }else if(redisData instanceof RedisHash){
            int del = ((RedisHash) redisData).del(fields);
            ctx.writeAndFlush(new RespInt(del));
        }else{
            throw new UnsupportedOperationException();
        }
    }

    @Override
    public void handle( RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData instanceof RedisHash) {
            int del = ((RedisHash) redisData).del(fields);
        }
    }
}
